﻿using JmShared;
using SuperWebSocket.SubProtocol;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WebSocketServer.Filters;

namespace WebSocketServer.Commands
{
    [LoggedInValidationFilter(Order = 0)]
    [LogTimeCommandFilter(Order = 1)]
    public class DeviceStatusUpdate : JsonSubCommand<JiveClientSession, DeviceStatus>
    {
        protected override void ExecuteJsonCommand(JiveClientSession session, DeviceStatus status)
        {
            if (status == null) throw new ArgumentNullException("status", "status is null");
            ChatClient client = session.ChatClient;

            if (status.IsActive.GetValueOrDefault() == true && client.IsActive == false)
            {
                client.IsActive = true;
                client.ProcessQueue();
              //  session.SendClientList(false);
                //session.ChatClient.ResetDeliveredMessageCount();
            }
            else
            {
                if (status.IsActive.GetValueOrDefault() == false && client.IsActive == true)
                    client.UpdateDeviceSync();
                client.IsActive = status.IsActive;
            }

            if (status.ClientStatus.HasValue && client.User.ClientStatus != status.ClientStatus)
            {
                client.User.ClientStatus = status.ClientStatus.Value;
                client.User.TimestampAfk = (client.User.ClientStatus == ClientStatus.Afk) ? DateTime.UtcNow : (DateTime?)null;
                status.TimeStampAfk = DateTime.UtcNow;
            }
            session.AppServer.SendToAll(status, session, false, true);
        }
    }
}
